/*
 *
 * Copyright (c) 2001-2018 泛微软件.
 * 泛微协同商务系统,版权所有.
 * 
 */
package weaver.fna.invoice.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.weaver.general.Util;
import net.coobird.thumbnailator.Thumbnails;
import weaver.fna.invoice.Constants;
import weaver.fna.invoice.common.FnaInvoiceCommon;
import weaver.general.BaseBean;

import org.apache.commons.codec.binary.Base64;
import weaver.hrm.User;

/**
 * @author zhangwj
 * @Jan 23, 2019
 */
public class ImageUtil {
	
	/**
	 * 图片转换
	 * @param fileData
	 * @return
	 * @throws Exception
	 */
	public static byte[] transformImage(String fileData) throws Exception{
		imageCheck(fileData);
		BaseBean bb = new BaseBean();
		byte[] imageByte = Base64.decodeBase64(fileData);
		long fileLen = imageByte.length;
		//大于2.5M,进行压缩
		if (fileLen > Constants.MAX_BYTES) {
			bb.writeLog("图片当前大小" + fileLen + ",需要压缩...");
			imageByte = compressImage(imageByte);
		}else{
			bb.writeLog("图片当前大小" + fileLen + ",不需要压缩...");
		}
		if (imageByte.length == 0) {
			throw new Exception("图片出现问题，请联系系统管理员!");
		}
		/*ByteArrayInputStream byteArrayInputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			byteArrayInputStream = new ByteArrayInputStream(imageByte);
			byteArrayOutputStream = new ByteArrayOutputStream();
			Thumbnails.of(byteArrayInputStream).useExifOrientation(false).scale(1).outputQuality(1d).toOutputStream(byteArrayOutputStream);
			String base64 = readImageBase64(byteArrayOutputStream);
			imageByte = Base64.decodeBase64(base64.replace("data:image/jpeg;base64,", ""));
		} catch (Exception e) {
		}finally{
			try {
				if(byteArrayOutputStream!=null){
					byteArrayOutputStream.close();
				}
			} catch (Exception e0) {}
			try {
				if(byteArrayInputStream!=null){
					byteArrayInputStream.close();
				}
			} catch (Exception e0) {}
		}*/
		return imageByte;
	}
	
	private static void imageCheck(String fileData) throws Exception{
		if ("".equals(fileData)) {
			throw new Exception("请选择正确的图片文件!");
		}
	}
	
	/**
	 * 图片压缩
	 * @param imageBytes
	 * @return
	 */
	private static byte[] compressImage(byte[] imageBytes){
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes);
		ByteArrayOutputStream byteArrayOutputStream = null;
		BaseBean bb = new BaseBean();
		try {
			int count = 5;
			double quality = 1d;
			while(quality > 0){
				quality = quality - 0.2d;
				byteArrayInputStream = new ByteArrayInputStream(imageBytes);
				byteArrayOutputStream = new ByteArrayOutputStream();
				//压缩图片
				Thumbnails.of(byteArrayInputStream).scale(quality).outputQuality(quality).toOutputStream(byteArrayOutputStream);
				if(byteArrayOutputStream.toByteArray().length <= Constants.MAX_BYTES){
					break;
				}
				count--;
				if(count == 0) {
					break;
				}
			}
			bb.writeLog("压缩质量：",quality);
		} catch (Exception e) {
			new BaseBean().writeLog("压缩出现错误：", e.getMessage());
		} finally {
			try {
				if(byteArrayOutputStream!=null) {
					byteArrayOutputStream.close();
				}
			} catch (Exception e) {
				bb.writeLog("出现错误：", e.getMessage());
			}
			try {
				if(byteArrayInputStream!=null) {
					byteArrayInputStream.close();
				}
			} catch (Exception e) {
				bb.writeLog("出现错误：", e.getMessage());
			}
		}
		return byteArrayOutputStream.toByteArray();
	}
	
	/**
	 * 图片截取
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @param imageBytes
	 * @return
	 * @throws Exception
	 */
	public static String cutImg(int x,int y,int w,int h,byte[] imageBytes,String orientation) throws Exception {
		ByteArrayInputStream byteArrayInputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			byteArrayInputStream = new ByteArrayInputStream(imageBytes);
			Thumbnails.of(byteArrayInputStream).sourceRegion(x, y, w, h).size(w, h).rotate(Util.getDoubleValue(orientation,0.00)).toOutputStream(byteArrayOutputStream);
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if(byteArrayOutputStream!=null) {
					byteArrayOutputStream.close();
				}
			} catch (Exception e) {
			}
			try {
				if(byteArrayInputStream!=null) {
					byteArrayInputStream.close();
				}
			} catch (Exception e) {
			}
		}
		String base64 = readImageBase64(byteArrayOutputStream);
		return base64;
    }
	
	/**
	 * 图片存储
	 * @param base64
	 * @return
	 * @throws Exception
	 */
	public static int saveImage(String base64, User user) throws Exception{
		base64 = base64.replaceFirst("data:image/jpeg;base64,", "");
		byte[] imageByte = Base64.decodeBase64(base64);
		int imageid = FnaInvoiceCommon.saveImage(imageByte,user);
		return imageid;
	}
	
	/**
	 * 获取图片base64
	 * @param byteArrayOutputStream
	 * @return
	 * @throws Exception
	 */
	private static String readImageBase64(ByteArrayOutputStream byteArrayOutputStream) throws Exception{
		String base64 = "";
		try{
			base64 = "data:image/jpeg;base64,"+Base64.encodeBase64String(byteArrayOutputStream.toByteArray());
		}finally{
			try {
				if(byteArrayOutputStream!=null) {
					byteArrayOutputStream.close();
				}
			} catch (Exception e) {
			}
		}
		return base64;
	}
}
